//app.js
/**
 * https://developers.weixin.qq.com/miniprogram/dev/quickstart/basic/framework.html#%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%9A%84%E5%90%AF%E5%8A%A8
 *
 * 小程序启动之后，在 app.js 定义的 App 实例的 onLaunch 回调会被执行。
 * App() 函数用来注册一个小程序。接受一个 object 参数，其指定小程序的生命周期函数等。
 * https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html
 */
var config = require('config.js')
// const  updateManager = wx.getUpdateManager
App({
    /*应用程序全局数据*/
    globalData: {
        url: 'http://cdn2.pluslegal.cn/image/mini/xz/',
        hasLogin: false,
        openid: null,
        userInfo: null,
        sessionKey: null,
        mSocketTask: null,
        socketOpen: false
    },
    onLaunch: function () {
        console.log('App Launch')
        var that = this;
        //首页背景音乐
        this.bgMusic = wx.createInnerAudioContext();
        this.bgMusic.src = this.globalData.url + 'bg4.mp3';
        // this.bgMusic.play();
        this.globalData.bgMusic = that.bgMusic;

        this.bgMusic.onEnded(function () {
            //that.bgMusic.play();
        })
        //冲榜音乐
        this.bgMusicT = wx.createInnerAudioContext();
        this.bgMusicT.src = this.globalData.url + 'bg5.mp3';
        this.globalData.bgMusicT = that.bgMusicT;
        this.bgMusicT.onEnded(function () {
            //that.bgMusicT.play();
        })
        //闯关音乐
        this.bgMusicF = wx.createInnerAudioContext();
        this.bgMusicF.src = this.globalData.url + 'bg2.mp3';
        this.globalData.bgMusicF = that.bgMusicF;
        this.bgMusicF.onEnded(function () {
           // that.bgMusicF.play();
        })
        //答对音乐
        this.bgMusicR = wx.createInnerAudioContext();
        this.bgMusicR.src = this.globalData.url + 'right.mp3';
        this.globalData.bgMusicR = that.bgMusicR;
        //答错音乐
        this.bgMusicW = wx.createInnerAudioContext();
        this.bgMusicW.src = this.globalData.url + 'wrongs.mp3';
        this.globalData.bgMusicW = that.bgMusicW;


        //法律考试音乐
        this.bgMusicExam = wx.createInnerAudioContext();
        this.bgMusicExam.src = this.globalData.url + 'exam_bg.mp3';
        console.log('bg' + this.bgMusicExam.src)
        this.globalData.bgMusicExam = that.bgMusicExam;
        this.bgMusicExam.onEnded(function () {
           // that.bgMusicExam.play();
        })


        // 展示本地存储能力
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)
        this.globalData.hasLogin = false;
        // 登录
        wx.login({
            success: res => {
                console.log(res.code)
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                wx.request({
                    url: config.appLogin,
                    method: 'POST',
                    data: {
                        noncestr: Date.now(),
                        code: res.code
                    },
                    success: function (result) {
                        if (result.data.success == 0) {
                            that.globalData.hasLogin = true;
                            that.globalData.openid = result.data.rows.openid;
                            that.globalData.sessionKey = result.data.rows.sessionKey;
                            try {
                                var isFirst = wx.getStorageSync('isFirst')
                                console.log(isFirst)
                                if (isFirst != 1) {
                                    wx.setStorageSync('isFirst', 1);
                                } else {
                                    try {
                                        wx.setStorageSync('isFirst', 2);
                                    } catch (e) {
                                    }
                                }
                            } catch (e) {
                                // Do something when catch error
                            }

                            that.getUserInfoData();
                        }
                    },

                    fail: function ({errMsg}) {
                        console.log('request fail', errMsg)
                    }
                })
            }
        })


        // updateManager.onCheckForUpdate(function (res) {
        //     // 请求完新版本信息的回调
        //     console.log(res.hasUpdate)
        // })

        // updateManager.onUpdateReady(function () {
        //     wx.showModal({
        //         title: '更新提示',
        //         content: '新版本已经准备好，是否重启应用？',
        //         success: function (res) {
        //             if (res.confirm) {
        //                 // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
        //                 updateManager.applyUpdate()
        //             }
        //         }
        //     })

        // })

        // updateManager.onUpdateFailed(function () {
        //     // 新的版本下载失败
        //     wx.showModal({
        //         title: '更新提示',
        //         content: '新版本下载失败',
        //         showCancel: false
        //     })
        // })

    },
  onLoad:function(){
    if (wx.canIUse("getUpdateManager")) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })

          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })

    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    
  },
    connectSocket: function () {
        if (!this.globalData.mSocketTask || !this.globalData.socketOpen) {
            var that = this;

            var socketTask = wx.connectSocket({
                url: config.socketHost,
                header: {
                    'openid': that.globalData.openid
                },
                success: function (res) {
                    console.log("websocket创建成功·····");
                }
            })
            this.globalData.mSocketTask = socketTask;

        }
    },
    getUserInfoData: function () {
        // 获取用户信息
        var that = this;
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            console.log("faceUrl -----------");
                            this.globalData.userInfo = res.userInfo;
                            this.globalData.rawData = res.rawData;
                            this.globalData.signature = res.signature;
                            this.globalData.encryptedData = res.encryptedData;
                            this.globalData.iv = res.iv;//////dwaawdawdawdawdaw
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                            //获取用户信息成功之后 提交数据到服务器
                            that.postUserInfo();

                        }
                    })
                }
            }
        })

    },

    /**
     * 向自己的服务器提交用户信息
     */
    postUserInfo: function () {
        var that = this;
        wx.request({
            url: config.postUserInfo,
            method: "POST",
            data: {
                sessionKey: that.globalData.sessionKey,
                rawData: that.globalData.rawData,
                signature: that.globalData.signature,
                encryptedData: that.globalData.encryptedData,
                iv: that.globalData.iv
            },
            success: function (res) {
                if (res.data.success == 0) {
                    console.log("向服务器提交用户信息成功")
                }
            },

            fail: function (error) {
                console.log(error)
            }
        })
    },


    onShow: function () {
        console.log('App Show')
    },
    onHide: function () {
        console.log('App Hide')
    },


    /**
     * 判断是否授权，否则打开授权
     */
    openAuthPage: function () {
        var that = this;
        if (!that.globalData.userInfo) {
            console.log("判断是否授权，否则打开授权");
            //未授权
            wx.navigateTo({
                url: '../authorization/authorization'
            })
            return;
        }

    },
    /**
     * 保存图片到手机
     */
    saveImgToPhotosAlbumTap: function (url) {
        var that = this;
        var imgUrl = url;
        console.log(imgUrl);
        wx.downloadFile({
            url: imgUrl,
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function (res) {
                        wx.showToast({
                            title: '成功',
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: function (res) {
                        console.log(res)
                    }
                })
            },
            fail: function () {
                console.log('fail')
            }
        })
    }


})